using System;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Configuration.Design;

namespace Microsoft.Practices.Repository.Configuration.Design
{
	sealed class RepositoryFactorySectionBuilder 
	{
		private readonly RepositoryFactorySectionNode _repositoryFactorySectionNode;
		private readonly IConfigurationUIHierarchy _hierarchy;
		private RepositoryFactorySection _repositoryFactorySection;

		public RepositoryFactorySectionBuilder(IServiceProvider serviceProvider, RepositoryFactorySectionNode repositoryFactorySectionNode) 
		{
			_repositoryFactorySectionNode = repositoryFactorySectionNode;
			_hierarchy = ServiceHelper.GetCurrentHierarchy(serviceProvider);
		}

		
		public RepositoryFactorySection Build()
		{
			_repositoryFactorySection = new RepositoryFactorySection();
			if (!_repositoryFactorySectionNode.RequirePermission)	// don't set if false
				_repositoryFactorySection.SectionInformation.RequirePermission = _repositoryFactorySectionNode.RequirePermission;
			BuildRepositories();
			return _repositoryFactorySection;
		}

		private void BuildRepositories()
		{
			IList<ConfigurationNode> repositories = _hierarchy.FindNodesByType(_repositoryFactorySectionNode, typeof(RepositoryNode));
			foreach (ConfigurationNode node in repositories)
			{
                RepositoryNode repositoryNode = (RepositoryNode)node;
				_repositoryFactorySection.Repositories.Add(new RepositoryElement(repositoryNode.InterfaceType, repositoryNode.RepositoryType));
			}
		}		
	}
}
